package team.future.joke.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.mongodb.WriteResult;

import team.future.joke.entity.Joke;

/**
 * Title: JokeDaoImpl.java<br>
 * Description: <br>
 * Copyright (c) 未来工作室版权所有 2015    <br>
 * Create DateTime: 2015年9月1日 下午8:14:39 <br>
 * @author futurezhu
*/
@Service("jokeDao")
public class JokeDaoImpl extends BaseMongoDaoImpl<Joke> {

	@Autowired
	private MongoOperations mongoTemplate;

	@Override
	public Joke getObject(Query query) {
		return mongoTemplate.findOne(query, Joke.class);
	}

	@Override
	public List<Joke> getObjectPage(Query query, int pageIndex, int pageSize) {
		if (pageIndex > 1) {
			query.skip(pageSize * (pageIndex - 1));
		}
		query.limit(pageSize);
		return mongoTemplate.find(query, Joke.class);
	}

	@Override
	public int updateObject(Query query, Update update) {
		WriteResult res = mongoTemplate.updateFirst(query, update, Joke.class);
		return res.getN();
	}

	@Override
	public void insertObject(Joke joke) {
		mongoTemplate.insert(joke);
	}

	@Override
	public List<Joke> getObjectList(Query query) {
		return mongoTemplate.find(query, Joke.class);
	}

	@Override
	public void deleteObject(Query query) {
		mongoTemplate.remove(query, Joke.class);
	}

	@Override
	public long countNum(Query query) {
		long num = mongoTemplate.count(query, Joke.class);
		return num;
	}

	@Override
	public Joke findObjectById(String id) {
		Query query = new Query(Criteria.where("id").is(id));
		return mongoTemplate.findOne(query, Joke.class);
	}
}
